package fw.server;

import java.net.*;
import java.io.*;

public class SocketProcessor extends Thread{

	private Socket socket;
	private BufferedReader br;
	private PrintStream ps;
	
	public SocketProcessor(Socket socket){
		this.socket = socket;
		try {
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			ps = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run(){
		try {
			processRequest();
		
			br.close();
			ps.flush();
			ps.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void processRequest() throws IOException{
		String firstLine = br.readLine();
		System.out.println(firstLine);
		String[] firstLineArgs = firstLine.split(" ");
		
		if(firstLineArgs.length != 3){
			sendError(400, "request error!");
			return;
		}
		
		String fileName = firstLineArgs[1];
		
		sendResponse(fileName);
		
	}
	
	public void sendError(int code, String msg) throws IOException{
		ps.println("HTTP/1.0 "+code + " " + msg);
		ps.println("content-type: text/html");
		
	}
	
	public void sendResponse(String fileName) throws IOException{
		File file = new File(WebServer.WEB_ROOT + fileName);
		System.out.println(file.getAbsolutePath());
		if(file.exists()){
			InputStream is = new FileInputStream(file);
			byte[] bytes = new byte[(int)file.length()];
			is.read(bytes);
			ps.println("HTTP/1.0 200 queryfile");
			ps.println("Content-length:" + file.length());
			ps.println();
			ps.write(bytes);
		}else{
			sendError(404, "File not found!");
			return;
		}

	}
}
